package copyengine.dataLayer.query.database
{
	import copyengine.dataLayer.query.server.CEServerQueryManger;
	import copyengine.utils.debug.CELog;

	import org.puremvc.as3.interfaces.INotification;

	public class CEDatabaseQueryDefaultImpl extends CEDatabaseQueryBasic
	{
		private static const SUFFIX:String = "::CEDatabaseQueryDefaultImpl";

		private var dto:CEDatabaseExcuteServerQueryDTO;

		public function CEDatabaseQueryDefaultImpl(_name:String, _param:Object, _localDatabase:ICEDatabase)
		{
			super(_name, _param, _localDatabase);
		}

		override public function onRegister():void
		{
			if (isCanGetDataFromLocalDatabase())
			{
				finishDatabaseQuery();
			}
			else
			{
				dto = dto == null ? getDTO() : dto;
				CEServerQueryManger.instance.excuteServerQuery(dto.serverQueryName,
															   dto.serverQueryName + SUFFIX,
															   dto.serverQueryWeight,
															   dto.serverQueryParam);
			}
		}

		override public function listNotificationInterests():Array
		{
			//延迟请求DTO对象
			dto = dto == null ? getDTO() : dto;
			//Locale 的请求不会含有DTO(及不会向服务器端发送请求)
			if (dto != null)
			{
				return [dto.serverQueryName + SUFFIX];
			}
			else
			{
				return [];
			}
		}

		override public function handleNotification(notification:INotification):void
		{
			handleRpcResult(notification.getBody());
			if (isHandleResultFinishImmediately())
			{
				finishDatabaseQuery();
			}
			else
			{
				CELog.log("child DQ need call finishDatabaseQuery() when handle result finished");
			}
		}

		/**
		 * check is can get data from local database, if can not get data then call server query
		 */
		protected function isCanGetDataFromLocalDatabase():Boolean
		{
			if (getResultData() == null)
			{
				return false;
			}
			else
			{
				return true;
			}
		}

		protected function isHandleResultFinishImmediately():Boolean
		{
			return true;
		}

		protected function getDTO():CEDatabaseExcuteServerQueryDTO
		{
			return null;
		}

		protected function handleRpcResult(_result:Object):void
		{
			throw new Error("child class should override this function");
		}

	}
}
